
<template>
    <div class="container">
      <div id="myExam">
        <div class="title">日志中心</div>
        <div class="wrapper">
          <ul class="top">
            <li class="order"><i class="el-icon-a-041" style="font-size: 20px;"> 日记列表</i></li>
            <li class="order">
              <el-button type="text" @click="daKai()">打开</el-button>
            </li>
            <el-dialog title="选择题" :visible.sync="dialogFormVisible">
              <el-form :model="form">
                <el-form-item label=""  style="display">
                 {{form.question}}
                </el-form-item>
                <el-form-item label="选项">
                <el-radio-group v-model="form.selectedOption">
                <el-radio label="A" >{{form.x1}}</el-radio>
                <el-radio label="B" >{{form.x2}}</el-radio>
                <el-radio label="C" >{{form.x3}}</el-radio>
                <el-radio label="D" >{{form.x4}}</el-radio>
                </el-radio-group>
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendXuan()">确 定</el-button>
              </div>
              <div v-if="showDisplay">
            <!-- 这里放置你要展示的内容 -->
            <el-card class="box-card">
              分数：{{score}}<br>
              答案：<br>
              {{form.answer}}
              解析：<br>
                {{form.analysis}}
            </el-card>
          </div>
            </el-dialog>
            <li class="search-li">
              <div class="icon">
                <input type="text" placeholder="日记标题" class="search" v-model="key"/><i
                class="el-icon-search"></i>
              </div>
            </li>
            <li>
              <el-button type="primary" @click="search()" icon="el-icon-a-042">搜索日记</el-button>
            </li>
          </ul>
          <ul class="paper" v-loading="loading">
            <li @click="toExamMsg(item)" class="item" v-for="(item, index) in pagination.records" :key="index">
              <h4>{{ item.title }}</h4>
              <p class="name">日记内容-{{ item.text }}</p>
              <div class="info">
                <i class="el-icon-time"></i><span>{{ item.diaryDate.substr(0, 10) }}</span>

              </div>
            </li>
          </ul>
          <div class="pagination">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="pagination.current" :page-sizes="[6, 10, 20, 40]" :page-size="pagination.size"
                           layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
            </el-pagination>
          </div>
        </div>
      </div>

      <el-button @click="table = true" size="small" round>
        最新学习报告
      </el-button>
      <el-drawer title="最新学习报!" :visible.sync="table" direction="rtl" size="50%">
        <el-table :data="gridData">
          <el-table-column property="date" label="日期" width="150"></el-table-column>
          <el-table-column property="name" label="科目" width="200"></el-table-column>
          <el-table-column property="address" label="学习情况"></el-table-column>
        </el-table>
        学习总建议

      </el-drawer>

    </div>

  </template>

  <script>

  export default {
    // name: 'myExam'
    data() {
      return {
        voiceText: '',
        showFixedBox: false,
        timeoutId: null,

        loading: false,
        key: null, //搜索关键字
        allExam: null, //所有考试信息
        pagination: {
          records: [],
          current: 1, //当前页
          total: null, //记录条数
          size: 6, //每页条数
          pages: '',
        },
        table: false,//弹出框
        dialog: false,
        gridData: [{
          date: '2024-05-02',
          name: '计算机网络',
          address: 'ip地址计算'
        }, {
          date: '2024-05-04',
          name: '计算机导论',
          address: ' 整体学习'
        }, {
          date: '2024-05-01',
          name: '软件工程',
          address: '工程化软件'
        }, {
          date: '2024-05-03',
          name: '操作系统',
          address: '进程线程'
        }],
        timer: null,
        //添加弹框
        dialogFormVisible: false,
        form: {
          date: '',
          text: '',
          title: '',
          question: '问题1',
          x1:'选项1',
          x2:'选项2',
          x3:'选项3',
          x4:'选项4',
          selectedOption:'',
          answer: '',
         text: '',
         title: '',
         analysis:'',
          zongwenti:'我国西部地区人口容量明显小于东部地区，其首要原因是（　　）A开放程度低B水资源匮乏C人均消费水平低D科技水平低',
        },
        formLabelWidth: '120px',
        isRecording: false,
        mediaRecorder: null,
        chunks: [],
        showDisplay:false,
        score:null,

      };
    },
    created() {
      this.getDiaryInfo();
      this.loading = true;
      console.log(this.pagination.current, this.pagination.size);
    },
    methods: {

        //处理问题分解
        chuli(questionStr) {
    // 使用正则表达式分割字符串
    const parts = questionStr.match(/^(.*?)([A-Z])\s*(.*?)\s*([A-Z])\s*(.*?)\s*([A-Z])\s*(.*?)\s*([A-Z])\s*(.*)$/);
    if (parts) {
  // 分割成功，分别赋值
  this.form.question = parts[1]; // 题目部分
  this.form.x1 = parts[3]; // A之后B之前的值
  this.form.x2 = parts[5]; // B之后C之前的值
  this.form.x3 = parts[7]; // C之后D之前的值
  this.form.x4 = parts[9]; // D之后的值
    } else {
       console.error('题目格式不匹配');
    }

},
daKai(){
this.sendQuestion();
this.dialogFormVisible = true;
this.chuli(this.form.zongwenti);

},
sendXuan(){
    this.sendExam();
    this.showDisplay = true;
},
//发送选项
async sendExam() {
      try {
        // 准备发送的数据
        const dataToSend = {//答案,id,
          id: this.$cookies.get("cid"),//用户id
          myAnswer: this.form.selectedOption, // 答案
        };

        // 发送 GET 请求到端口 8081
        const response = await fetch('http://localhost:8081/history-question-by-ai?id=' + dataToSend.id + '&myAnswer=' + encodeURIComponent(dataToSend.myAnswer), {
          method: 'GET', // 注意这里改为 GET 请求
          headers: {
            'Content-Type': 'application/json'
          }
        });

        // 解析服务器返回的响应数据
        const data = await response.json();

        console.log('选项为：', this.form.selectedOption);
        console.log('从服务器接收到的信息：', data.data.score);//接收data
        this.score=data.data.score;
        this.analysis=data.data.analysis;
        this.answer=data.data.answer;

      } catch (error) {
        console.error('发送请求时出错：', error);
      }
    },
    //改变当前记录条数
    handleSizeChange(val) {
      this.pagination.size = val
      this.getAiQuestionInfo()
    },
    //改变当前页码，重新发送请求
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getAiQuestionInfo()
    },
    //发送出题
async sendQuestion() {
      try {
        // 准备发送的数据
        const dataToSend = {//答案,id,
          id: this.$cookies.get("cid"),//用户id
          pointList:  // --------------------------------知识点
        };

        // 发送 GET 请求到端口 8081
        const response = await fetch('http://localhost:8081/history-question-by-ai?id=' + dataToSend.id + '&myAnswer=' + encodeURIComponent(dataToSend.myAnswer), {
          method: 'GET', // 注意这里改为 GET 请求
          headers: {
            'Content-Type': 'application/json'
          }
        });

        // 解析服务器返回的响应数据
        const data = await response.json();

        console.log('选项为：', this.form.selectedOption);
        console.log('从服务器接收到的信息：', data.data.score);//接收data
        this.form.zongwenti=data.data.question;

      } catch (error) {
        console.error('发送请求时出错：', error);
      }
    },
    //改变当前记录条数
    handleSizeChange(val) {
      this.pagination.size = val
      this.getAiQuestionInfo()
    },
    //改变当前页码，重新发送请求
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getAiQuestionInfo()
    },




      //获取当前所有考试信息
      getExamInfo() {
        this.$axios(
          `/api/exams/${this.pagination.current}/${this.pagination.size}`
        )
          .then((res) => {
            this.pagination = res.data.data;
            this.loading = false;
            console.log(this.pagination);
          })
          .catch((error) => {
            console.log(error);
          });
      },
      //获取日志
      async getDiaryInfo() {
        const queryParams = new URLSearchParams({
          userId: this.$cookies.get("cid"),
          pageNo: 1,
          pageSize: 6
        });

        const url = `http://localhost:8081/user-diary?${queryParams}`;

        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then((res) => {
            // 检查响应是否成功
            if (!res.ok) {
              throw new Error(`HTTP error! status: ${res.status}`);
            }

            // 解析 JSON 格式的响应体
            return res.json();
          })
          .then((data) => {
            // 获取解析后的数据并处理
            // 在这里你可以将数据保存到变量中，或者执行其他操作
            this.pagination = data.data;
            this.loading = false;
            console.log(data);
          })
          .catch((error) => {
            console.error('Fetch Error:', error);
          });
      },
      //改变当前记录条数
      handleSizeChange(val) {
        this.pagination.size = val;
        this.getExamInfo();
      },
      //改变当前页码，重新发送请求
      handleCurrentChange(val) {
        this.pagination.current = val;
        this.getExamInfo();
      },
      //搜索试卷
      search() {
        this.$axios("/api/exams").then((res) => {
          if (res.data.code == 200) {
            let allExam = res.data.data;
            let newPage = allExam.filter((item) => {
              return item.source.includes(this.key);
            });
            this.pagination.records = newPage;
          }
        });
      },
      //跳转到试卷详情页
      toExamMsg(exam) {
        if (exam.examDate > this.formatDateNow()) {
          this.$message({
            message: "考试时间未到",
            type: "error",
          });
          return;
        }
        this.$router.push({
          path: "/examMsg",
          query: {examCode: exam.examCode},
        });
      },
      formatDateNow() {
        var date = new Date(); // 当前日期时间
        var year = date.getFullYear(); // 年份
        var month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份+1
        var day = ("0" + date.getDate()).slice(-2); // 日
        return year + "-" + month + "-" + day;
      },
      addtext() {
        console.log(this.$cookies.get("cid"), this.form.date, this.form.text);
        this.serverAddtext();
        this.dialogFormVisible = false;
        this.getDiaryInfo();
      },
      async serverAddtext() {
        try {
          // 准备发送的数据
          const dataToSend = {
            userId: this.$cookies.get("cid"),
            diaryDate: this.form.date,
            text: this.form.text, // 表单
            title: this.form.title,
          };
          // 发送 POST 请求到端口 8081
          const response = await fetch('http://localhost:8081/user-diary', {
            method: 'POST', // 注意这里改为 POST 请求
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(dataToSend)
          });

          // 解析服务器返回的响应数据
          const data = await response.json();

          console.log('从服务器接收到的信息：', data);//接收
          // this.textshow = data.data;

        } catch (error) {
          // 处理错误
          console.error('发送数据时出错：', error);
        }
      },

    },
  };
  </script>

  <style lang="less" scoped>
  .container {
    display: flex;
    justify-content: space-between; /* 让内部元素左右对齐 */
    align-items: flex-end; /* 让按钮位于容器底部 */
  }

  .pagination {
    padding: 20px 0px 30px 0px;

    .el-pagination {
      display: flex;
      justify-content: center;
    }
  }

  .paper {
    h4 {
      cursor: pointer;
    }
  }

  .paper .item a {
    color: #000;
  }

  .wrapper .top .order {
    cursor: pointer;
  }

  .wrapper .top .order:hover {
    color: #0195ff;
    border-bottom: 2px solid #0195ff;
  }

  .wrapper .top .order:visited {
    color: #0195ff;
    border-bottom: 2px solid #0195ff;
  }

  .item .info i {
    margin-right: 5px;
    color: #0195ff;
  }

  .item .info span {
    margin-right: 14px;
  }

  .paper .item {
    width: 380px;
    border-radius: 4px;
    padding: 20px 30px;
    border: 1px solid #eee;
    box-shadow: 0 0 4px 2px rgba(217, 222, 234, 0.3);
    transition: all 0.6s ease;
  }

  .item {
    cursor: pointer;
  }

  .paper .item:hover {
    box-shadow: 0 0 4px 2px rgba(140, 193, 248, 0.45);
    transform: scale(1.03);
  }

  .paper .item .info {
    font-size: 14px;
    color: #88949b;
  }

  .paper .item .name {
    font-size: 14px;
    color: #88949b;
  }

  .paper * {
    margin: 20px 0;
  }

  .wrapper .paper {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
  }

  .top .el-icon-search {
    position: absolute;
    right: 10px;
    top: 10px;
  }

  .top .icon {
    position: relative;
  }

  .wrapper .top {
    border-bottom: 1px solid #eee;
    margin-bottom: 20px;
  }

  #myExam .search-li {
    margin-left: auto;
  }

  .top .search-li {
    margin-left: auto;
  }

  .top li {
    display: flex;
    align-items: center;
  }

  .top .search {
    margin-left: auto;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #eee;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
  }

  .top .search:hover {
    color: #0195ff;
    border-color: #0195ff;
  }

  .wrapper .top {
    display: flex;
  }

  .wrapper .top li {
    margin: 20px;
  }

  #myExam {
    width: 980px;
    margin: 0 auto;
  }

  #myExam .title {
    margin: 20px;
  }

  #myExam .wrapper {
    background-color: #fff;
  }
  </style>
